import pygame
import sys
import traceback
from pygame.locals import *
from random import *

import paopao
import turtle
import fish

# 初始化pygame模块
pygame.init()
# 规定窗体大小
bg_size = width, height = 800, 600
# 创建窗体
screen = pygame.display.set_mode(bg_size)
# 设置窗体标题
pygame.display.set_caption("大龟吃小鱼")
# 定义时钟
clock = pygame.time.Clock()

# 载入音乐文件
# 背景音乐
pygame.mixer.music.load("music/bg_music.ogg")
pygame.mixer.music.set_volume(0.3)
# 死亡音效
die_sound = pygame.mixer.Sound("music/die.wav")
die_sound.set_volume(0.2)
# 吃鱼音效
eat_sound = pygame.mixer.Sound("music/eat.wav")
eat_sound.set_volume(0.2)
# 警告音效
warn_sound = pygame.mixer.Sound("music/warn1.wav")
warn_sound.set_volume(0.3)
# 海水音效
seaWater_sound = pygame.mixer.Sound("music/seaWater.wav")
seaWater_sound.set_volume(0.3)
# 乌龟变大音效
bigger_sound = pygame.mixer.Sound("music/bigger.wav")
bigger_sound.set_volume(0.3)

# 存放小、中、大和鲨鱼
fishes = pygame.sprite.Group()
# 存放鲨鱼的列表
shark_fish = []
# 载入鱼的图像文件
# 小鱼
sfish_img = ["images/sFish1.png", "images/sFish2.png", "images/sFish3.png"]
# 中鱼
mfish_img = ["images/mFish1.png", "images/mFish2.png"]
# 大鱼
bfish_img = ["images/bFish1.png", "images/bFish2.png"]
# 鲨鱼
shark_img = ["images/shark1.png", "images/shark2.png"]


# 初始实例化鱼对象
def init_fishes():
    # 方向随机的3种小鱼各12条
    for img in sfish_img:
        for i in range(12):
            num = randint(1, 2)
            fish_ = fish.Fish(bg_size, img, 0, 3, num)
            fishes.add(fish_)
    # 方向随机的2种中鱼各4条
    for img in mfish_img:
        for i in range(4):
            num = randint(1, 2)
            fish_ = fish.Fish(bg_size, img, 2, 3, num)
            fishes.add(fish_)
    # 方向随机的2种大鱼各4条
    for img in bfish_img:
        for i in range(4):
            num = randint(1, 2)
            fish_ = fish.Fish(bg_size, img, 4, 3, num)
            fishes.add(fish_)

    # 方向随机的2种鲨鱼各1条
    for img in shark_img:
        num = randint(1, 2)
        fish_ = fish.Shark(bg_size, img, num)
        shark_fish.append(fish_)


# 载入图标文件
warn_img = "images/warn.png"
unpause_img = "images/unpause.png"
pause_img = "images/pause.png"
game_index = "images/index.png"


# 绘制图标到窗体
def load_icon(img, rect):
    image = pygame.image.load(img).convert_alpha()
    screen.blit(image, rect)


# 绘制文字到窗体
def load_text(content, size, color, position):
    font = pygame.font.SysFont("kaiti", size)
    text = font.render(content, True, color)
    screen.blit(text, position)


# 绘制移动的鱼类到窗体
def load_fishes():
    # “大、小、中”鱼
    for fish_ in fishes:
        if fish_.live:
            fish_.swim()
            fish_.display_fish()
        else:
            fish_.reset()
            fish_.live = True

    for fish_ in shark_fish:
        fish_.swim()
        fish_.display_fish()


# 鲨鱼的碰撞检测
def shark_collide(tur):
    for fish_ in shark_fish:
        # 鲨鱼与“大、小、中”鱼
        array = pygame.sprite.spritecollide(fish_, fishes, False, pygame.sprite.collide_mask)
        if array:
            for i in array:
                i.live = False
        # 鲨鱼与乌龟
        if pygame.sprite.collide_rect_ratio(0.8)(fish_, tur):
            tur.live = False


# 乌龟的碰撞检测
def turtle_collide(tur):
    for fish_ in fishes:
        if pygame.sprite.collide_rect_ratio(0.8)(fish_, tur):
            # 乌龟吃鱼
            if tur.size > fish_.size:
                eat_sound.play()
                fish_.live = False
                # 吃鱼得分
                if fish_.size == 0:
                    tur.score += 10
                elif fish_.size == 2:
                    tur.score += 20
                elif fish_.size == 4:
                    tur.score += 30
            # 乌龟被吃
            else:
                eat_sound.play()
                tur.live = False


# 躲避与追赶
def elude_pursue(tur):
    for fish_ in fishes:
        # 对在窗体中，并与乌龟近的鱼进行检测
        if 0 < fish_.rect.left < width - fish_.rect.width and tur.rect.left - 100 < fish_.rect.left < tur.rect.left + 100:
            # 小鱼躲避机制
            if fish_.size < tur.size:
                if int(abs(fish_.rect.bottom - tur.rect.top)) < 50:
                    if fish_.direction != tur.direction:
                        fish_.direction = tur.direction
                    fish_.rect.bottom -= fish_.speed
                elif int(abs(tur.rect.bottom - fish_.rect.top)) < 50:
                    if fish_.direction != tur.direction:
                        fish_.direction = tur.direction
                    fish_.rect.top += fish_.speed
            # 大鱼追赶机制
            elif fish_.size > tur.size:
                if int(abs(fish_.rect.bottom - tur.rect.top)) < 40:
                    if fish_.rect.left > tur.rect.left:
                        fish_.direction = 1
                    elif fish_.rect.left <= tur.rect.left:
                        fish_.direction = 2
                    fish_.rect.bottom += fish_.speed
                elif int(abs(tur.rect.bottom - fish_.rect.top)) < 40:
                    if fish_.rect.left > tur.rect.left:
                        fish_.direction = 1
                    elif fish_.rect.left <= tur.rect.left:
                        fish_.direction = 2
                    fish_.rect.top -= fish_.speed


def main():
    # 无限循环播放BGM
    #pygame.mixer.music.play(-1)
    # 实例化泡泡对象
    pao = paopao.paoPao()
    # 实例化乌龟对象
    tur = turtle.Turtle()
    # 实例化各种鱼类对象
    init_fishes()

    # 运行条件
    running = True
    # 暂停条件
    paused = False

    while running:
        # 获取光标位置
        now_pos = pygame.mouse.get_pos()

        for event in pygame.event.get():
            if event.type == QUIT:
                # 解决关闭窗口不退出问题
                pygame.quit()
                # 退出游戏
                sys.exit()
            if event.type == KEYDOWN:
                if event.key == K_SPACE:
                    paused = not paused

        if not paused:
            # 绘制背景图片
            screen.blit(pygame.image.load('images/bg_image.jpg').convert_alpha(), (0, 0))

            # 绘制得分
            load_text("Score : %s" % str(tur.score), 30, (255, 255, 255), (10, 5))

            # 绘制非暂停图标
            load_icon(unpause_img, (750, 10))

            # 捕食与追赶
            elude_pursue(tur)

            # 绘制鱼类图案
            load_fishes()

            # 鲨鱼相关事件
            shark_collide(tur)

            # 乌龟相关事件
            turtle_collide(tur)
            # 乌龟大小级
            if 500 <= tur.score < 1000:
                tur.size = 3
            if 1000 <= tur.score:
                tur.size = 5
            tur.bigger()

            # 设置光标不可见
            pygame.mouse.set_visible(False)
            # 将光标画在pygame，默认光标的位置
            tur.rect.center = pygame.mouse.get_pos()

        if paused:
            # 设置光标可见
            pygame.mouse.set_visible(True)
            # 绘制暂停图标
            load_icon(pause_img, (750, 10))
        else:
            # 设置光标不可见
            pygame.mouse.set_visible(False)

            # 获取新的光标位置
            new_pos = pygame.mouse.get_pos()

            # 绘制乌龟图案,并判断游戏结束
            if tur.live:
                tur.display_turtle(now_pos, new_pos)
            else:
                # 设置光标可见
                pygame.mouse.set_visible(True)
                # 停止播放背景音乐
                pygame.mixer.music.stop()
                # 播放死亡音乐
                die_sound.play()
                paused = True
                # 绘制游戏结束
                load_text("Game Over！！！", 30, (255, 0, 0), (300, 200))

            # 泡泡相关事件
            pao.rise()
            pao.display_paopao()

        # 刷新页面
        pygame.display.flip()
        # 设置帧率为60帧/秒
        clock.tick(60)


if __name__ == "__main__":
    try:
        main()
    except SystemExit:
        pass
    except:
        traceback.print_exc()
        pygame.quit()
        input()

